use super::util::contains_todo;
use crate::handlers::handle_question::openai::tool_functions::function_keys;
use crate::models::message_templates;
use crate::models::{ProjectConfig, ProjectContent};
use std::fs;
use std::path::PathBuf;

pub fn load_long_question_from_project(project_config: &ProjectConfig) -> Option<ProjectContent> {
    let path = &project_config.path;
    let handle_ext = &project_config.handle_ext;

    if path.is_dir() {
        if let Some(project_content) =
            search_directory_recursive(path, handle_ext, &project_config.exclude_folders)
        {
            let output_content = message_templates::ProjectCodeQuestionTemplate {
                file_path: project_content.file_path.clone(),
                function_key: function_keys::WRITE_FILE_KEY.to_string(),
                content: project_content.content.clone()
            }
            .to_string();

            return Some(ProjectContent {
                file_path: project_content.file_path,
                content: output_content,
            });
        }
    }
    None
}

fn search_directory_recursive(
    dir: &PathBuf,
    handle_ext: &Vec<String>,
    exclude_folders: &Option<Vec<String>>,
) -> Option<ProjectContent> {
    for entry in fs::read_dir(dir).unwrap() {
        let entry = entry.unwrap();
        let file_path = entry.path();

        if file_path.is_dir() {
            if let Some(exclude_folders) = exclude_folders {
                if exclude_folders.contains(&file_path.to_string_lossy().to_string()) {
                    continue;
                }
            }
            if let Some(result) =
                search_directory_recursive(&file_path, handle_ext, exclude_folders)
            {
                return Some(result);
            }
        } else if file_path.is_file() {
            if let Some(ext) = file_path.extension() {
                if handle_ext.contains(&ext.to_string_lossy().to_string()) {
                    if let Ok(content) = fs::read_to_string(&file_path) {
                        if contains_todo(&content) {
                            return Some(ProjectContent {
                                file_path: file_path.clone(),
                                content,
                            });
                        }
                    }
                }
            }
        }
    }
    None
}
